package com.dennytech.tac.widget;

import java.io.FileInputStream;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.util.AttributeSet;

public class LocalImageView extends NetworkThumbView {
	public LocalImageView(Context context) {
		super(context);
	}

	public LocalImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public LocalImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected LoadTask createLoadTask() {
		return new LocalIconLoadTask(this);
	}

	protected static class LocalIconLoadTask extends CachedLoadTask {
		AssetManager assets;

		public LocalIconLoadTask(NetworkImageView p) {
			super(p);
			assets = p.getContext().getResources().getAssets();
		}

		@Override
		public Bitmap preDoInBackground(String... params) {
			final String url = params[0];
			int i = url.lastIndexOf("/");
			if (i > 0) {
				urlLocks.lock(url);
				try {
					//
					// check memcache first
					//
					Bitmap cbitmap = memcache.get(url);
					if (cbitmap != null)
						return cbitmap;
					
					Bitmap bitmap = null;
					
					if (url.startsWith("/xxx/")) {
						String icon = url.substring(i + 1);
						InputStream ins = assets.open("localicon/" + icon);
						bitmap = BitmapFactory.decodeStream(ins);
						ins.close();
					} else {
						bitmap = parseThumbnail(url);
					}
					
					if (bitmap != null)
						memcache.put(url, bitmap);
					return bitmap;
				} catch (Exception e) {
				} finally {
					urlLocks.unlock(url);
				}
			}

			return null;
		}

		public Bitmap parseThumbnail(String file) {
			int sampling = 1;
			try {
				FileInputStream ins = new FileInputStream(file);
				Options opt = new Options();
				opt.inJustDecodeBounds = true;
				BitmapFactory.decodeStream(ins, null, opt);
				ins.close();

				int size = opt.outWidth > opt.outHeight ? opt.outWidth
						: opt.outHeight;
				if (size < 1400)
					sampling = 1;
				else if (size < 2800)
					sampling = 2;
				else
					sampling = 4;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}

			Bitmap showBitmap = null;

			for (; sampling <= 8 && showBitmap == null; sampling *= 2) {
				try {
					FileInputStream ins = new FileInputStream(file);
					Options opt = new Options();
					opt.inSampleSize = sampling;
					showBitmap = BitmapFactory.decodeStream(ins, null, opt);
					ins.close();
				} catch (OutOfMemoryError oom) {
					System.gc();
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}

			return showBitmap;
		}
	}
}
